#include "hanwidget.h"
static QList<QChar> allAssignedHan() {
    QList<QChar> list;
    // CJK Unified Ideographs 主区
    for (uint c = 0x4E00; c <= 0x9FFF; ++c) list.append(QChar(c));
    qDebug() << "基本汉字个数：" << list.size();
    // 扩展 A 区
    for (uint c = 0x3400; c <= 0x4DBF; ++c) list.append(QChar(c));
    qDebug() << "加扩展A区：" << list.size();
    return list;
}

HanWidget::HanWidget(QWidget* parent) : QWidget{parent} {
    m_chars = allAssignedHan();
    setFont(QFont("Noto Sans SC", 12));  // ① 保证有字形
}

QSize HanWidget::sizeHint() const {
    QFontMetrics fm(m_font);
    int w = fm.horizontalAdvance("中") * m_cols;
    int h = fm.height() * ((m_chars.size() + m_cols - 1) / m_cols);
    return {w, h};
}

void HanWidget::paintEvent(QPaintEvent*) {
    QPainter p(this);
    p.setFont(m_font);
    QFontMetrics fm(m_font);
    int cw = fm.horizontalAdvance("中");
    int ch = fm.height();
    for (int i = 0; i < m_chars.size(); ++i) {
        int row = i / m_cols;
        int col = i % m_cols;
        QRect rc(col * cw, row * ch, cw, ch);
        // ② 只画字体确实包含的字
        if (fm.inFont(m_chars[i]))
            p.drawText(rc, Qt::AlignCenter, QString(m_chars[i]));
        else
            p.fillRect(rc, QColor(240, 240, 240));  // 没字形就灰底
    }
}
